<template>
	<div class="textbook_box">
		<el-form :model="editForm" ref="editForm" :inline="true">
			<el-row>
				<el-col :span="4">
					<el-form-item label="教材名称：" prop="textbookName">
						<div class="text-ellipsis">{{ editForm.textbookName }}</div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="专业：" prop="majorId">
						<div class="text-ellipsis"><span v-for="item in majors" v-if="item.id == editForm.majorId">{{
							item.name }}</span></div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="版本号：" prop="version">
						<div class="text-ellipsis">{{ editForm.version }}</div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="状态：" prop="state">
						<div class="text-ellipsis"><span v-for="item in states" v-if="item.value == editForm.state">{{
							item.label }}</span></div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="创建人：" prop="createUserName">
						<div class="text-ellipsis">{{ editForm.createUserName }}</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="textbook_new_tree">
			<div class="textbook_new_tree_head">
				<span> 教材章节分配情况</span>
			</div>
			<div class="textbook_new_tree_body">
				<div class="textbook_new_tree_body_list beautifulScroll" id="textbook_cont">
					<div class="textbook_new_tree_body_empty" v-if="treeList.length == 0">
						<div class="textbook_new_tree_body_emptycont">
							<img src="@/assets/images/textbook_new_tree_body_emptycont.png" alt="">
							<div>暂无教材章节~</div>
						</div>
					</div>
					<div class="data_card_list" v-for="chapter in treeList">
						<div class="chapter_text">
							<div class="chapter_text_in">
								<div class="chapter_text_all text-ellipsis" @click="changeOpen(chapter)">
									<span class="chapter_text_allicon">
										<i class="el-icon-arrow-right " v-show="!openChapters.includes(chapter.id)"></i>
										<i class="el-icon-arrow-down " v-show="openChapters.includes(chapter.id)"></i>
									</span>
									<span class="chapter_text_span">
										<i class="el-icon-folder-opened" />
									</span>
									<div class="text-ellipsis pointer">
										{{ chapter.name }}
									</div>
								</div>
							</div>
						</div>
						<div class="section_text_all" v-show="openChapters.includes(chapter.id)"
							v-if="chapter.children && chapter.children.length">
							<div class="section_text"
								:class="(section.teacherId ? 'tree-' + section.teacherId : '') + ' ' + (teacherId == section.teacherId ? 'active' : '')"
								v-for="section in chapter.children">
								<span class="chapter_text_allicon">
									<i class="el-icon-collection-tag" />
								</span>
								<div class="section_text_in">
									<div class="chapter_text_all text-ellipsis">
										{{ section.name }}
									</div>
								</div>
								<div class="arco_tree_btns text-ellipsis">
									{{ section.teacherName }}
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="textbook_new_cont">
			<div class="textbook_new_tree_head">
				教师列表
			</div>
			<div class="textbook_new_cont_body">
				<div class="textbook_new_tree_body_right">
					<div class="textbook_new_tree_body_right_btn">
						<el-input v-model="teacherInfo" size="small" placeholder="请输入教师姓名搜索" style='width: 230px;'
							clearable />
						<el-button size="small" @click='getTreeList'>搜索</el-button>
						<el-button type='primary' size="small" @click="openAdd('add')">新增分配</el-button>
					</div>
					<div class="textbook_new_teachers clearfix">
						<div class="textbook_new_teacher" :class="teacherId == item.teacherId ? 'active' : ''"
							@click="rowClickShow(item)" v-for="item in teacherList">
							<div class="textbook_new_teacher1">
								<div class="textbook_new_teacher2">
									<img src="@/assets/images/nv.png" v-if="!item.headPortraitUrl && item.sex == 'F'">
									<img src="@/assets/images/nan.png" v-if="!item.headPortraitUrl && item.sex == 'M'">
									<img :src="baseurl + item.headPortraitUrl" v-if="item.headPortraitUrl">
								</div>
								<div class="textbook_new_teacher3">
									<div class="textbook_new_teacher31">{{ item.teacherName }}</div>
									<div class="textbook_new_teacher32">{{ item.teacherNo }}</div>
								</div>
							</div>
							<div class="textbook_new_teacher4">
								负责小节数量：<span>{{ item.sectionNum || 0 }}节</span>
								<div class="fr">
									<div class="textbook_new_tree_body_btn " @click.stop="openEdit(item)">
										<i class="el-icon-edit" />编辑
									</div>
									<div class="textbook_new_tree_body_btn " @click.stop="openDelete(item)">
										<i class="el-icon-delete" />删除
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="textbook_new_cont_body_cover" v-if="addFormShow">
			<div class="textbook_new_teacher_share" :class="addForm.type == 'add' ? '' : 'active'">
				<div class="textbook_new_teacher_share_close" @click.stop="resetAdd"><i class="el-icon-close"></i></div>
				<div class="textbook_new_teacher_main">
					<div class="textbook_new_teacher_mainitem" v-if="addForm.type == 'add'">
						<div class="textbook_new_tree_head">
							教材章节分配
						</div>
						<div class="textbook_new_tree_body">
							<div class="textbook_new_tree_body_search">
								<el-input v-model="teacherName" size="small" placeholder="输入姓名进行过滤"
									style='width: 100%;' clearable />
							</div>
							<div class="textbook_new_tree_body_list beautifulScroll">
								<div class="textbook_new_teacher_list_head">
									<div class="textbook_new_teacher_list_td1">头像</div>
									<div class="textbook_new_teacher_list_td2">姓名</div>
									<div class="textbook_new_teacher_list_td3">工号</div>
								</div>
								<div class="textbook_new_teacher_list_tr"
									:class="addForm.teacherId == item.teacherId ? 'active' : ''" @click="rowClick(item)"
									v-for="item in teacherSelects">
									<div class="textbook_new_teacher_list_td1">
										<div class="textbook_new_teacher_list_icon">
											<img src="@/assets/images/nv.png"
												v-if="!item.headPortraitUrl && item.sex == 'F'">
											<img src="@/assets/images/nan.png"
												v-if="!item.headPortraitUrl && item.sex == 'M'">
											<img :src="baseurl + item.headPortraitUrl" v-if="item.headPortraitUrl">
										</div>
									</div>
									<div class="textbook_new_teacher_list_td2 text-ellipsis">{{ item.teacherName }}
									</div>
									<div class="textbook_new_teacher_list_td3 text-ellipsis">{{ item.teacherNo }}</div>
								</div>
							</div>
						</div>
					</div>
					<div class="textbook_new_teacher_mainitem" :class="addForm.type == 'add' ? '' : 'active'">
						<div class="textbook_new_tree_head">
							章节列表
						</div>
						<div class="textbook_new_tree_body">
							<div class="textbook_new_tree_body_search">
								<el-input v-model="chapterName" size="small" placeholder="输入章节名进行过滤"
									style='width: 100%;' clearable />
							</div>
							<div class="textbook_new_tree_body_list beautifulScroll">
								<el-tree :data="treeSelect" node-key='id' :props="props" show-checkbox ref='addTree'
									:default-expand-all="true" :filter-node-method="filterNode"
									:check-strictly='checkStrictly' @check-change="handelSectionChange">
									<template slot-scope="{ node, data }">
										<div class="textbook_tree_item text-ellipsis">{{ data.name }}
											<span class="textbook_tree_itemuser" v-if="data.teacherName">
												[{{ data.teacherName || '' }}]
											</span>
										</div>
									</template>
								</el-tree>
							</div>
						</div>
					</div>
					<div class="textbook_new_teacher_mainitem" :class="addForm.type == 'add' ? '' : 'active'">
						<div class="textbook_new_tree_head">
							已选内容
						</div>
						<el-form :model="addForm" :rules="rules" ref="addForm" v-if="addFormShow" label-width="0"
							class="textbook_new_tree_body back">
							<div class="textbook_info_selectsmall">
								<div class="textbook_top">
									已选教师：
								</div>
								<div class="textbook_cont_select">
									<el-tag :closable="addForm.type == 'add'" @close="handleClose"
										v-if="addForm.teacherId">
										{{ addForm.teacherName }}
									</el-tag>
									<el-form-item prop="teacherId"></el-form-item>
								</div>
							</div>
							<div class="textbook_info_selectsection">
								<div class="textbook_top">
									已选：<span class="mainColor">{{ addForm.sectionInfoReqs.length }}小节</span>
									<div class="fr">
										<div class="textbook_new_tree_body_btn " @click.stop="handleDeleteAll()">
											<i class="el-icon-delete" />清空全部
										</div>
									</div>
								</div>
								<div class="textbook_cont_select list beautifulScroll">
									<div class="textbook_cont_section text-ellipsis" v-for="(item, index) in addForm.sectionInfoReqs">
										<span class="chapter_text_allicon">
											<i class="el-icon-collection-tag" />
										</span>
										<span class="text-ellipsis">{{ item.chapterSectionName }}</span>
										<div class="textbook_cont_sectionclose" @click='handleDeleteItem(item, index)'>
											<i class="el-icon-close"></i>
										</div>
									</div>
									<el-form-item prop="sectionInfoReqs">
									</el-form-item>
								</div>
							</div>
						</el-form>
					</div>
				</div>
				<div class="textbook_new_teacher_share_btns">
					<el-button @click="resetAdd">取 消</el-button>
					<el-button type="primary" @click="addData" :disabled='dataloading'>确 定</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import { heightToTop } from '@/utils/index.js'
import { majorList } from '@/api/major.js'
import { selectTextbookDetail, selectTextbookDirectoryByUserId, teacherSectionInfoList } from "@/api/textbook.js"
import { getTextbookSectionTeacherList, saveTextbookSectionTeacher, removeTextbookSectionTeacher } from "@/api/textbookSectionTeacher.js"
export default {
	data() {
		return {
			openChapters: [],
			teacherId: '',
			chapterName: '',
			teacherName: '',
			teacherInfo: '',
			teacherList: [],
			teacherNum: 0,
			treeList: [],
			dataloading: false,
			textbookId: this.$route.query.textbookId,
			majors: [],
			states: [{
				value: 1,
				label: "启用"
			}, {
				value: 2,
				label: "禁用"
			}],
			editForm: {
				textbookId: '',
				textbookName: '',
				majorId: '',
				version: '',
				state: '',
				prefaceHtml: '',
				textbookCover: '',
			},
			addFormShow: false,
			addForm: {
				type: "",
				teacherId: "",
				teacherName: "",
				sectionInfoReqs: [],
				sectionInfoReqsIds: [],
			},
			rules: {
				teacherId: [{ required: true, message: '请选择教师', trigger: 'blur' }],
				sectionInfoReqs: [{ required: true, message: '请选择章节', trigger: 'blur' }],
			},
			teacherSelects: [],
			treeSelect: [],
			props: {
				label: 'name',
				value: 'id',
			},
			checkStrictly: true,
		}
	},
	created() {
		this.getMajorList();
		this.getDateList();
		this.getTreeList();
	},
	watch: {
		chapterName(val) {
			this.$refs.addTree.filter(val);
		},
		teacherName(val) {
			console.log(val);
			if (val) {
				var teacherSelects = []
				this.teacherSelectsOri.map(item => {
					if (item.teacherName.indexOf(val) > -1) {
						teacherSelects.push(item)
					}
				})
				this.teacherSelects = teacherSelects
			} else {
				this.teacherSelects = this.teacherSelectsOri;
			}
		}
	},
	methods: {
		changeOpen(chapter) {
			if (this.openChapters.includes(chapter.id)) {
				var sliceIndex = this.openChapters.indexOf(chapter.id);
				this.openChapters.splice(sliceIndex, 1)
			} else {
				this.openChapters.push(chapter.id)
			}
		},
		resetAdd() {
			this.addForm = {
				type: "",
				teacherId: "",
				teacherName: "",
				sectionInfoReqs: [],
				sectionInfoReqsIds: [],
			}
			this.addFormShow = false;
		},
		addData() {
			this.$refs.addForm.validate(valid => {
				if (valid) {
					saveTextbookSectionTeacher({
						...this.addForm,
						textbookId: this.textbookId,
					}).then(res => {
						if (res.code == '200') {
							this.$message.success({
								message: res.message,
							});
							this.resetAdd();
							this.getTreeList();
						}
					})
				}
			});
		},
		rowClick(item) {
			this.addForm.teacherId = item.teacherId;
			this.addForm.teacherName = item.teacherName;
			this.$refs.addForm.clearValidate();
		},
		handleClose() {
			this.addForm.teacherId = '';
			this.addForm.teacherName = '';
		},
		handleDeleteItem(item, index) {
			this.addForm.sectionInfoReqs.splice(index, 1)
			this.$refs.addTree.setChecked(item.chapterSectionId, false, false);
		},
		handleDeleteAll(item, index) {
			this.addForm.sectionInfoReqs = []
			this.$refs.addTree.setCheckedKeys([]);
		},
		handelSectionChange() {
			var checkedNodes = this.$refs.addTree.getCheckedNodes(false, true);
			var sectionInfoReqs = [];
			checkedNodes.map(item => {
				if (item.parentId) {
					sectionInfoReqs.push({
						textbookChapterId: item.parentId,
						chapterSectionId: item.id,
						chapterSectionName: item.name,
					})
				}
			})
			this.addForm.sectionInfoReqs = sectionInfoReqs;
			this.$refs.addForm.clearValidate();
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
		},
		openAdd(type) {
			teacherSectionInfoList({
				textbookId: this.textbookId,
				isDispense: 2
			}).then(res => {
				this.teacherSelectsOri = res.data || [];
				this.teacherSelects = res.data || [];
				selectTextbookDirectoryByUserId({
					textbookId: this.textbookId,
				}).then(async res => {
					var treeSelect = [];
					res.data.chapterDirectoryDtos.map(item => {
						item.children = [];
						item.sectionDirectoryDtos.map(it => {
							if (it.chapterSectionId) {
								var disabled = false;
								if (type == 'add' && it.teacherId) {
									disabled = true;
								}
								if (type == 'edit' && it.teacherId && it.teacherId != this.addForm.teacherId) {
									disabled = true;
								}
								item.children.push({
									disabled: disabled,
									parentId: item.textbookChapterId,
									parentName: item.chapterName,
									id: it.chapterSectionId,
									name: it.sectionName,
									teacherId: it.teacherId,
									teacherName: it.teacherName,
								})
							}
						})
						treeSelect.push({
							id: item.textbookChapterId,
							name: item.chapterName,
							children: item.children
						})
					})
					this.treeSelect = treeSelect
					this.checkStrictly = true;
					this.addFormShow = true;
					this.addForm.type = type
					this.addOpend()
				});
			})
		},
		openEdit(item) {
			this.addForm.teacherId = item.teacherId;
			this.addForm.teacherName = item.teacherName;
			var sectionInfoReqsIds = [];
			for (let key in item.chapterSectionIds) {
				sectionInfoReqsIds.push(key)
				item.chapterSectionIds[key].map(it => {
					sectionInfoReqsIds.push(it)
				})
			}
			this.addForm.sectionInfoReqsIds = sectionInfoReqsIds || [];
			this.openAdd('edit')
		},
		addOpend() {
			this.$nextTick(() => {
				if (this.addForm.sectionInfoReqsIds && this.addForm.sectionInfoReqsIds.length > 0) {
					this.$refs.addTree.setCheckedKeys(this.addForm.sectionInfoReqsIds);
				}
				this.checkStrictly = false;
			})
		},
		openDelete(item) {
			this.$confirm('是否删除该教师分配的章节?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				removeTextbookSectionTeacher({
					textbookId: this.textbookId,
					teacherId: item.teacherId
				}).then(async res => {
					if (res.code == '200') {
						this.$message({
							message: '删除成功',
							type: 'success'
						})
						this.getTreeList();
					} else {
						this.$message({
							message: res.message,
							type: 'error'
						})
					}
				})
			}).catch(() => { });
		},
		getMajorList() {
			majorList({}).then(res => {
				this.majors = res.data || []
			})
		},
		rowClickShow(item) {
			if (this.teacherId == item.teacherId) {
				this.teacherId = '';
			} else {
				this.teacherId = item.teacherId;
				let firstEle = document.querySelector('.tree-' + item.teacherId)
				let fatherEle = document.querySelector('#textbook_cont')
				if (firstEle && fatherEle) {
					var heightToTopLength = heightToTop(firstEle, fatherEle);
					fatherEle.scrollTo(0, heightToTopLength - 8);
				}
			}
		},
		getTreeList() {
			getTextbookSectionTeacherList({
				textbookId: this.textbookId,
				teacherInfo: this.teacherInfo
			}).then(res => {
				this.teacherList = res.data || [];
				this.teacherNum = res.data.length || 0;
			})
			selectTextbookDirectoryByUserId({
				textbookId: this.textbookId,
			}).then(async res => {
				var treeList = [];
				var openChapters = [];
				res.data.chapterDirectoryDtos.map(item => {
					item.children = [];
					item.sectionDirectoryDtos.map(it => {
						if (it.chapterSectionId) {
							item.children.push({
								parentId: item.textbookChapterId,
								parentName: item.chapterName,
								id: it.chapterSectionId,
								name: it.sectionName,
								teacherId: it.teacherId,
								teacherName: it.teacherName,
							})
						}
					})
					openChapters.push(item.textbookChapterId)
					treeList.push({
						id: item.textbookChapterId,
						name: item.chapterName,
						children: item.children
					})
				})
				this.treeList = treeList || [];
				this.openChapters = openChapters || [];
			});

		},
		getDateList() {
			selectTextbookDetail({
				textbookId: this.textbookId
			}).then(async res => {
				this.editForm = { ...res.data };
			});
		},
		closeCheck() {
			var view = this.$route;
			this.$store.dispatch('tagsView/delView', view).then(({
				visitedViews
			}) => {
				if (this.isActive(view)) {
					this.toLastView(visitedViews, view)
				}
			})
		},
		isActive(route) {
			return route.path === this.$route.path
		},
		toLastView(visitedViews, view) {
			const latestView = visitedViews.slice(-1)[0]
			if (latestView) {
				this.$router.push(latestView)
			} else {
				if (view.name === 'Dashboard') {
					this.$router.replace({
						path: '/redirect' + view.fullPath
					})
				} else {
					this.$router.push('/')
				}
			}
		},
	},
}
</script>